package com.chongqing.shiro.service.filter;


import com.chongqing.shiro.model.entity.Permission;
import com.chongqing.shiro.service.impl.PermissionServiceImpl;
import com.chongqing.shiro.util.CoreConst;
import com.chongqing.shiro.util.SpringContextHolder;
import com.chongqing.shiro.util.VerificationUtil;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 过滤链
 * -------------------
 * @Author: YangXingfu
 * @Date: 2019/01/04 17:41
 */


/**
 * 初始化权限
 */
@Service
public class FilterChainDefinitions {

    @Autowired
    private PermissionServiceImpl permissionService;

    public Map<String, String > loadFilterChainDefinitionos() {
        //权限控制map，从数据库中获取
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
        filterChainDefinitionMap.put("/static/**", "anon");
        filterChainDefinitionMap.put("/register", "anon");
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/error/**", "anon");
//        filterChainDefinitionMap.put("kickout", "anon");
        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/js/**", "anon");
        filterChainDefinitionMap.put("/img/**", "anon");
        filterChainDefinitionMap.put("/libs/**", "anon");
        filterChainDefinitionMap.put("/favicon.ico", "anon");
        filterChainDefinitionMap.put("/verificationCode", "anon");

        List<Permission> permissions = permissionService.selectAll(CoreConst.STATUS_VALID);
        for (Permission permission : permissions) {
            if (!VerificationUtil.isEmpty(permission.getUrl()) && !VerificationUtil.isEmpty(permission.getPerms())) {
                String perm = "perms[" + permission.getPerms() + "]";
                filterChainDefinitionMap.put(permission.getUrl(), perm);
            }
        }

//        filterChainDefinitionMap.put("/**", "user,kickout");
        filterChainDefinitionMap.put("/**", "user");
        return filterChainDefinitionMap;

    }

    /**
     * 重载权限
     */
    public void updatePermissions() {
        ShiroFilterFactoryBean shiroFilterFactoryBean = SpringContextHolder.getBean(ShiroFilterFactoryBean.class);
        synchronized(shiroFilterFactoryBean) {
            AbstractShiroFilter shiroFilter = null;
            try {
                shiroFilter = (AbstractShiroFilter) shiroFilterFactoryBean.getObject();
            } catch (Exception e) {
                throw new RuntimeException("get ShiroFilter from shiroFilterFactoryBean error!");
            }

            PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
            DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();
            /*清空老权限*/
            manager.getFilterChains().clear();
            shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();
            shiroFilterFactoryBean.setFilterChainDefinitionMap(loadFilterChainDefinitionos());
            /*重新构建生成*/
            Map<String, String> chains = shiroFilterFactoryBean.getFilterChainDefinitionMap();
            for (Map.Entry<String, String> entry : chains.entrySet()) {
                String url = entry.getKey();
                String chainDefinition = entry.getValue().trim().replace(" ", "");
                manager.createChain(url, chainDefinition);
            }
        }
    }


}